using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using Templates;
using WebService.Nafania.ViewLayer.Model.ObjectView;

namespace WebService.Nafania.ViewLayer.Model.Base
{
	[DataContract]
	public class TemplateView
	{
		public override string ToString()
		{
			StringBuilder sb = new StringBuilder();
			sb.AppendFormat("Class: {0}\r\n", GetType().FullName);
			sb.AppendFormat("Name: {0}\r\n", Name);
			sb.AppendFormat("Data: {0}\r\n", Data);
			return sb.ToString();
		}

		private static TemplateView Instance(string name, Base.ObjectView data)
		{
			return new TemplateView()
			       	{
			       		Name = name.Trim(),
								Data = data
			       	};
		}

		public static TemplateView AsListText(string name, IEnumerable<object> obj)
		{
			var data = new ListTextView();
			var textViews = new List<TextView>();

			foreach (var o in obj)
			{
				if (o is IParse)
				{
					textViews.Add(new TextView() { Value = ((IParse)o).ParseToString(), });
				}
				else
				{
					textViews.Add(new TextView(){Value = o.ToString()});
				}
			}

			data.Values = textViews;
			return Instance(name, data);
		}

		public static TemplateView AsText(string name, object obj)
		{
			var data = new TextView()
			               	{
			               		Value = obj
			               	};
			return Instance(name, data);
		}

		public static TemplateView AsHidden(string name, object obj)
		{
			var data = new HiddenView()
			               	{
			               		Value = obj
			               	};
			return Instance(name, data);
		}

		public static TemplateView AsList(string name, object obj)
		{
			Type objType = obj.GetType();
			var data = objType.IsEnum
			               	? new ListView()
			               	  	{
			               	  		Value = objType.IsEnum ? (int) obj : obj,
			               	  		Values =
			               	  			(
			               	  				from x in Enum.GetNames(objType)
			               	  				let val = (int) Enum.Parse(objType, x)
			               	  				select new KeyValuePair{Key = val.ToString(), Value = x}
			               	  			).ToList()
			               	  	}
			               	: (ListView) null;

			return Instance(name, data);
		}

		[DataMember]
		public string Name { get; set; }

		[DataMember]
		public Base.ObjectView Data { get; set; }

		public override bool Equals(object obj)
		{
			if(obj == null) return false;

			return GetHashCode() == obj.GetHashCode();
		}

		public override int GetHashCode()
		{
			return ToString().GetHashCode();
		}
	}
}